# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import datetime
import logging
import pprint
import sys

from tornado import gen
from tornado.ioloop import IOLoop

from coin.base.config import Config
from coin.exchange.base.order_gateway import OrderSide, OrderType
from coin.exchange.binance.order_gateway import BinanceOrderGateway
from coin.exchange.binance.kr_rest.product import BinanceProduct
from coin.flow.simple_queue import SimpleQueue
import coin.flow.subscriber as flow_subscriber
from coin.exchange.binance.kr_rest.currency import BinanceCurrency
from coin.exchange.binance.kr_rest.public_client import BinancePublicClient


class TestDriver(object):
  def __init__(self, ioloop):
    self._ioloop = ioloop
    currencies = [BinanceCurrency.FromStrCurrency(currency) for currency in ('BTC', 'BNB')]
    products = [BinanceProduct.FromStr(symbol) for symbol in ('BNBBTC', 'XRPBTC')]
    self._og = BinanceOrderGateway(currencies,
                                   products,
                                   Config.from_config_filename('binance_pilot01'))
    queue = SimpleQueue('queue')
    self._og.start(queue, self._ioloop, flow_subscriber.from_queue(queue))
    self._ioloop.add_timeout(datetime.timedelta(seconds=5), self.print_balance)
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.loop)
    self._public_client = BinancePublicClient()

  def print_balance(self):
    if self._og.is_ready():
      print('------------------------')
      print(datetime.datetime.now())
      print('BTC', self._og.get_balance('BTC'))
      print('BNB', self._og.get_balance('BNB'))
      print('XRP', self._og.get_balance('XRP'))
      pprint.pprint(self._og.get_working_order())
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.print_balance)

  @gen.coroutine
  def loop(self):
    self._og.cancel_all()
    yield gen.sleep(5)
    xrp_btc_product = BinanceProduct.FromStr('XRP-BTC')

    while True:
      update = self._public_client.query_ticker(xrp_btc_product)
      last_price = update.msg.last
      min_value = 0.001  # Minimum value in terms of BTC.
      qty = round(min_value / last_price) + 2
      self._og.submit(xrp_btc_product, last_price * 1.01, qty, OrderSide.SELL, OrderType.LIMIT)
      self._og.submit(xrp_btc_product, last_price * 0.99, qty, OrderSide.BUY, OrderType.LIMIT)
      yield gen.sleep(10)
      self._og.cancel_all()


def main(argv):
  ioloop = IOLoop.current()
  TestDriver(ioloop)
  try:
    ioloop.start()
  except KeyboardInterrupt:
    pass


if __name__ == '__main__':
  logging.basicConfig(
      level='DEBUG',
      format='%(levelname)8s %(asctime)s.%(msecs)03d %(name)s] %(message)s',
      datefmt='%Y%m%d %H:%M:%S',
  )
  sys.exit(main(sys.argv))
